package m.jclecai.com.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import m.jclecai.com.R;
import m.jclecai.com.utils.http.HttpManager;

import static m.jclecai.com.utils.PackageCompareUtil.getIconResourceByPackage;


/**
 * Created by andy on 2017/8/17.
 * 这里我们要进行的一个操作就是进行一个下载；
 * 专门用来处理下载通知的一个类；
 *
 * 这里的话，以后还有一个操作就如果用户已经下载了的话，
 * 我们的弹窗就不能再是下载的，而是安装；
 */

public class DownloadService extends IntentService {


    private final int id =1;

    private long apkSize;

    boolean isSuccess=false;

    NotificationManager mNotificationManager;
    Notification mNotification;
    private Notification.Builder mBuilder;

    public static final String DOWNLOAD_URL="downloadUrl";
    public static final String APK_SIZE="apk_size";
    private String mDownLoadUrl;


    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public DownloadService(String name) {
        super(name);
    }

    public DownloadService() {
        this("default");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //这里我们执行一个下载登陆逻辑就行了
        apkSize = intent.getLongExtra(APK_SIZE, 0);
        mDownLoadUrl = intent.getStringExtra(DOWNLOAD_URL);
        if(apkSize == 0){
            Toast.makeText(this,"下载异常！",Toast.LENGTH_SHORT).show();
        }else{
            update();
        }
    }

    /**
     * 这里我们升级
     */
    private void update() {

        OkHttpClient okHttpClient = HttpManager.getInstance().getHttpClient();

        Request request = new Request.Builder().url(mDownLoadUrl).build();

        Call call = okHttpClient.newCall(request);

        File file = null;
        InputStream inputStream=null ;
        FileOutputStream fileOutputStream=null;
        long lastTime = System.currentTimeMillis();

        try {
            Response response = call.execute();

            if (response.isSuccessful()) {

                long total=0;
                ResponseBody body = response.body();

                //这里我们将从服务器下载apk；
                inputStream = body.byteStream();
                file = new File(Environment.getExternalStorageDirectory(), "cp.apk");
                fileOutputStream=new FileOutputStream(file);
                int length=0;
                byte[] bytes=new byte[1024];
                while ((length=inputStream.read(bytes))!=-1) {
                    fileOutputStream.write(bytes,0,length);
                    //这里的话，我们要做的一个操作就是显示进度；
                    total+=length;

                    System.out.println("total: "+total);

                    long currentTime =System.currentTimeMillis();
                    if (currentTime-lastTime>1000) {
                        //1秒钟采集一次；
                        int currentNum = (int) (100 * total / apkSize);//下载的百分比；
                        //更新进度条
                        mBuilder.setProgress(100, currentNum,false);
                        mBuilder.setContentText("下载进度:" + currentNum+"%");
                        mNotificationManager.notify(id, mBuilder.build());
                        lastTime=currentTime;
                    }

                }
            }
            isSuccess=true;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            //关闭
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (isSuccess) {
            mBuilder.setProgress(0, 0,false).setContentText("下载完成，点击安装！！！");

           // mBuilder.setFullScreenIntent(getPedingIntent(), true);


            mBuilder.setDefaults(Notification.DEFAULT_ALL); //这里可以悬挂几秒自动收起来
            mBuilder.setPriority(Notification.PRIORITY_HIGH);
            mBuilder.setContentIntent(getPedingIntent());
            Notification notification = mBuilder.build();
            notification.flags=Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(id, notification);

        }else{
            mBuilder.setProgress(0, 0,false).setContentText("下载失败，点击重试！！！");
            mBuilder.setContentIntent(getReTry());
            mNotificationManager.notify(id, mBuilder.build());
        }
    }

    private PendingIntent getReTry() {

        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra(APK_SIZE,apkSize);
        intent.putExtra(DOWNLOAD_URL,mDownLoadUrl);
        PendingIntent service = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return service;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startNotifycation();
    }

    /**
     * 打开通知的测试；
     */
    private void startNotifycation() {


        mNotificationManager=((NotificationManager) getSystemService(NOTIFICATION_SERVICE));

        mBuilder = new Notification.Builder(this);
        mBuilder.setContentTitle("正在更新...") //设置通知标题
                .setSmallIcon(getIconResourceByPackage()) //设置通知的小图标
                .setLargeIcon(BitmapFactory
                        .decodeResource(this.getResources(),
                                getIconResourceByPackage())) //设置通知的大图标
                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                .setPriority(Notification.PRIORITY_MAX) //设置通知的优先级：最大
                .setAutoCancel(false)//设置通知被点击一次是否自动取消
                .setContentText("下载进度:" + "0%")
                .setProgress(100, 0, false);
        mNotification = mBuilder.build();//构建通知对象

        mNotificationManager.notify(id, mNotification);
    }

    public PendingIntent getPedingIntent() {

        File file = new File(Environment.getExternalStorageDirectory(), "cp.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data=null;
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            //这里的话，我们在7.0是需要使用FileProvider;
            data = FileProvider.getUriForFile(this, "m.jclecai.com.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }else{
           data = Uri.fromFile(file);
        }

        intent.addCategory(Intent.CATEGORY_DEFAULT);

        intent.setDataAndType(data,
                "application/vnd.android.package-archive");

        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return pendingIntent;
    }
}
